package iec104tcp;


import lombok.extern.slf4j.Slf4j;
import model.ModusTable;
import org.joda.time.DateTime;
import service.ModusTableService;
import wei.yigulu.iec104.annotation.AsduType;
import wei.yigulu.iec104.apdumodel.Apdu;
import wei.yigulu.iec104.asdudataframe.ShortFloatType;
import wei.yigulu.iec104.asdudataframe.qualitydescription.IeMeasuredQuality;
import wei.yigulu.iec104.asdudataframe.typemodel.InformationBodyAddress;
import wei.yigulu.iec104.nettyconfig.Iec104MasterBuilder;
import wei.yigulu.netty.BaseProtocolBuilder;

import java.util.List;
import java.util.Map;

/**
 * 处理短浮点
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@AsduType(typeId = 13)
@Slf4j
public class HandleShortFloat extends ShortFloatType {

	ModusTableService modusTableService = ModusTableService.getInstance();

	/**
	 * 处理短浮点数据
	 */
	@Override
	public byte[][] handleAndAnswer(Apdu apdu) {
		apdu.getLog().trace("----------处理短浮点数据---------");
		BaseProtocolBuilder builder = apdu.getIec104Builder();
		if (builder != null && builder instanceof Iec104MasterBuilder) {
			Map<Integer, ModusTable> dataPoint = (Map<Integer, ModusTable>) builder.getConfigInfoMap().get("ModusTable");
			builder.getConfigInfoMap().put("lastReceiveTime", DateTime.now());
			HandleShortFloat handleShortFloat = (HandleShortFloat) apdu.getAsdu().getDataFrame();
			List<InformationBodyAddress> address = handleShortFloat.getAddresses();
			Map<IeMeasuredQuality, Float> dates = handleShortFloat.getDatas();
			int i = 0;
			ModusTable modusTable;
			//存入数据池
			if (apdu.getAsdu().getVsq().getSq() == 0) {
				apdu.getLog().info("------处理短浮点单一寻址-----");
				for (Map.Entry<IeMeasuredQuality, Float> e : dates.entrySet()) {
					if (!e.getKey().isGoodValue()){
						log.debug("品质描述异常");
						continue;
					}
					if (dataPoint.containsKey(address.get(i).getAddress())) {
						modusTable = dataPoint.get(address.get(i).getAddress());
						modusTableService.updateModusValue(modusTable.getIpIdentity(), modusTable.getId(), e.getValue() + "", "");
					}
					i++;
				}
			} else if (apdu.getAsdu().getVsq().getSq() == 1) {
				apdu.getLog().info("------处理短浮点连续寻址-----");
				i = address.get(0).getAddress();
				for (Map.Entry<IeMeasuredQuality, Float> e : dates.entrySet()) {
					if (!e.getKey().isGoodValue()){
						log.debug("品质描述异常");
						continue;
					}
					if (dataPoint.containsKey(i)) {
						modusTable = dataPoint.get(i);
						modusTableService.updateModusValue(modusTable.getIpIdentity(), modusTable.getId(), e.getValue() + "", "");
					}
					i++;
				}
			}

		}
		return null;
	}

}
